﻿using LuShanTea.Admin.Web.App_Start;
using LuShanTea.Admin.Web.Models;
using LuShanTea.IService;
using LuShanTea.Web.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LuShanTea.Admin.Web.Controllers
{
    public class AreaController : Controller
    {
        public IAreaService AreaService { get; set; }
        public ICityService CityService { get; set; }
        // GET: Area
        [CheckPermission("Area.List")]
        public ActionResult List()
        {
            var model = AreaService.GetAll();
            return View(model);
        }

        [HttpPost]
        [CheckPermission("Area.Delete")]
        public ActionResult Delete(long id)
        {
            AreaService.MarkDelete(id);
            return Json(new AjaxResult { Status = "ok" });
        }

        [HttpGet]
        [CheckPermission("Area.AddNew")]
        public ActionResult AddNew()
        {
            var model = CityService.GetAll();
            return View(model);
        }

        [HttpPost]
        [CheckPermission("Area.AddNew")]
        public ActionResult AddNew(AreaAddModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = MVCHelper.GetValidMsg(ModelState)});
            }
            var en = AreaService.GetByName(model.Name);
            if (en!=null)
            {
                if (en.CityId== model.CityId)
                {
                    return Json(new AjaxResult {Status="error", ErrorMsg="该市已存在该区域" });
                }
            }
            AreaService.AddNew(model.Name, model.CityId);
            return Json(new AjaxResult { Status = "ok"});
        }

        [HttpGet]
        [CheckPermission("Area.Edit")]
        public  ActionResult Edit(long id)
        {
            AreaEditListModel model = new AreaEditListModel();
            model.Area= AreaService.GetById(id);
            if (model.Area==null)
            {
                return Content("找不到该区域");
            }
            model.Cities = CityService.GetAll();
            return View(model);
        }

        [HttpPost]
        [CheckPermission("Area.Edit")]
        public ActionResult Edit(AreaEditModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = MVCHelper.GetValidMsg(ModelState) });
            }
            var en = AreaService.GetByName(model.Name);
            if (en != null)
            {
                if (en.CityId == model.CityId)
                {
                    return Json(new AjaxResult { Status = "error", ErrorMsg = "该市已存在该区域" });
                }
            }
            AreaService.Update(model.Id, model.Name, model.CityId);
            return Json(new AjaxResult { Status = "ok" });
        }

    }
}